package com.yc.cloud.socket.utils;

import com.yc.cloud.socket.service.SocketClient;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.WebSocket;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;
import org.springframework.stereotype.Service;

import java.net.URI;
import java.net.URISyntaxException;

/**
 * @author 杨智杰
 * @since 2021/9/24 9:47
 */
@Slf4j
@Service
public class SocketClientUtil {

    public static SocketClient socketClient;

    /**
     * 链接socket服务器
     *
     * @param uri
     */
    public void linkSocket(String uri) {
        linkSocket(uri, "");
    }

    /**
     * 链接socket服务端
     *
     * @param uri
     * @return
     */
    public void linkSocket(String uri, String msg) {
        WebSocketClient client = null;
        try {
            client = new WebSocketClient(new URI(uri), new Draft_6455()) {
                @Override
                public void onOpen(ServerHandshake serverHandshake) {
                    socketClient.onOpen(serverHandshake);
                }

                @Override
                public void onMessage(String msg) {
                    socketClient.onMessage(msg);
                }

                @Override
                public void onClose(int i, String s, boolean b) {
                    socketClient.onClose(i, s, b);
                }

                @Override
                public void onError(Exception e) {
                    socketClient.onError(e);
                }
            };
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        client.connect();
        while (!client.getReadyState().equals(WebSocket.READYSTATE.OPEN)) {
            log.info("正在连接...");
        }
        log.info("链接成功!");
        socketClient.sendMessage(client, msg);
    }
}
